﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;
using Provenance.Write.Api.Application.Command.Product;

namespace Provenance.Write.Api.Application.CommandHandler.Product
{
    public class UpdateProductInfoCommandHandler : IRequestHandler<UpdateProductInfoCommand, ApiResult>
    {
        private readonly IProductInfoRepository _productInfoRepository;
        private readonly ILogger<UpdateProductInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public UpdateProductInfoCommandHandler(IProductInfoRepository productInfoRepository, ILogger<UpdateProductInfoCommandHandler> logger, IMapper mapper)
        {
            _productInfoRepository = productInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpdateProductInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _productInfoRepository.GetAsync(x => x.ProductInfoId == request.ProductInfoId);
                obj= _mapper.Map(request, obj);
                await _productInfoRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error in UpdateProductInfoCommandHandler :" + ex.Message);
                return ApiResult.Failure("Error in UpdateProductInfoCommandHandler :" + ex.Message);
            }
        }
    }
}
